package com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.base.BaseHint;
import com.example.administrator.ygddriver.base.LogInformationBean;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.audit.AuditActivity;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.credentials.CredentialsActivity;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.credentials.FileRrequestBean;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.credentials.PhotoBean;
import com.example.administrator.ygddriver.into.login.driverjoin.weight.weightmessage.WeightMessageActivity;
import com.example.administrator.ygddriver.into.register.RegisterActivity;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.liteorm.SingleLiteOrm;
import com.example.administrator.ygddriver.tool.GlideImageLoader;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.SimpleToolbar;
import com.example.administrator.ygddriver.tool.UrlValuse;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zaaach.citypicker.CityPicker;
import com.zaaach.citypicker.adapter.OnPickListener;
import com.zaaach.citypicker.model.City;
import com.zaaach.citypicker.model.LocateState;
import com.zaaach.citypicker.model.LocatedCity;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 司机加盟界面
 */
public class SmallMessageActivity extends BaseActivity implements View.OnClickListener {
    private SimpleToolbar simpleToolbar;
    private LinearLayout mCityLl, mPhoneLl, mCredentialsLl;
    private TextView mCityTv;
    private Button mNextBtn;
    private TextView mPhotoTv;
    private int tag;
    private String mToken, mId, mPhotoBase64;
    private int REQUEST_CODE_SELECT = 12312;
    private PhotoBean mPhotoBean;
    private EditText mIdEt, mNameEt;
    private String c_drivertype;
    private String city, province, mAccount;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private ImageView mHeadIv;
    private ImagePicker imagePicker;
    private String mHeadPlace;
    private Bitmap mPhoneMp;

    @Override
    public int initLayout() {
        return R.layout.activity_small_message;
    }

    @Override
    public void initView() {
        simpleToolbar = findViewById(R.id.activity_small_message_stb);
        mCityLl = findViewById(R.id.activity_small_message_city_ll);
        mPhoneLl = findViewById(R.id.activity_small_message_phone_ll);
        mCredentialsLl = findViewById(R.id.activity_small_message_credentials_ll);
        mCityTv = findViewById(R.id.activity_small_message_city_tv);
        mNextBtn = findViewById(R.id.activity_small_message_next_btn);
        mPhotoTv = findViewById(R.id.activity_small_message_photo_tv);
        mIdEt = findViewById(R.id.activity_small_message_id_et);
        mNameEt = findViewById(R.id.activity_small_message_name_et);
        mHeadIv = findViewById(R.id.activity_small_message_heade_iv);
        mNextBtn.setOnClickListener(this);
        mCityLl.setOnClickListener(this);
        mPhoneLl.setOnClickListener(this);
        mCredentialsLl.setOnClickListener(this);
        mPhotoBean = new PhotoBean();
    }

    @Override
    public void initDate() {
        setIgPicker();
        imagePicker = ImagePicker.getInstance();
        mLocationClient = new LocationClient(this);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        setLocationClientOption();
        mLocationClient.start();
        setSimpleToolbar();
        c_drivertype = getIntent().getStringExtra("c_drivertype");
        LiteOrmTools.getInformation(UserBean.class, this, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                mToken = data.getC_token();
                mId = data.getC_id();
                mAccount = data.getC_account();
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });
        LiteOrmTools.getInformation(LogInformationBean.class, this, new LiteOrmTools.On<LogInformationBean>() {
            @Override
            public void hasData(LogInformationBean data) {
                mCityTv.setText(data.getC_city());
                mNameEt.setText(data.getC_name());
                mIdEt.setText(data.getC_idnumber());
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });
        RequestOptions requestOptions = new RequestOptions()
                .placeholder(R.mipmap.initial_head)
                .error(R.mipmap.initial_head)
                .fallback(R.mipmap.initial_head);
        String s = String.valueOf(Environment.getExternalStorageDirectory());
        Glide.with(this)
                .load(s + "/YGDDriver/Photo/" + mAccount + "HEAD_PHOTO.jpg")
                .apply(requestOptions)
                .into(mHeadIv);
    }

    private void setSimpleToolbar() {
        simpleToolbar.setMainTitle("司机加盟");
        simpleToolbar.setMainTitleColor("#000000");
        simpleToolbar.setBackIv(R.mipmap.left_title);
        simpleToolbar.setToolColor("#ffffff");
        simpleToolbar.setBackIvClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_small_message_city_ll:
                setCity();
                break;
            case R.id.activity_small_message_phone_ll:
                Intent intent = new Intent(this, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                intent.putExtra("tag", 1); // 调用前置摄像头
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                break;
            case R.id.activity_small_message_credentials_ll:
                Intent intent2 = new Intent(this, CredentialsActivity.class);
                intent2.putExtra("tag","1");
                startActivityForResult(intent2, 0x002);
                break;
            case R.id.activity_small_message_next_btn:
                if (judge(mNameEt.getText().toString(), mIdEt.getText().toString(), mCityTv.getText().toString())) {
                    initDriverAuthenticationHtml(mId, mNameEt.getText().toString(), mIdEt.getText().toString(), mCityTv.getText().toString(), mPhotoBean.getC_frontface(), mPhotoBean.getC_reverseside(), mPhotoBean.getC_onecarphoto(), mPhotoBean.getC_handheld(), mHeadPlace, c_drivertype, mToken);
                }
                break;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x002 && resultCode == 0x001) {
            Bundle bundle = data.getExtras();
            mPhotoBean = bundle.getParcelable("result");
            mPhotoTv.setText("上传完成");
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                imagePicker.getImageLoader().displayImage(this, images.get(0).path, mHeadIv, mHeadIv.getWidth(), mHeadIv.getHeight());
                mPhotoBase64 = bitmapToBase64(comp(BitmapFactory.decodeFile(images.get(0).path)));
                mPhoneMp = comp(BitmapFactory.decodeFile(images.get(0).path));
                initFileHtml(mPhotoBase64, "3", mToken);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    //司机端用户认证
    private void initDriverAuthenticationHtml(String c_id, final String c_name, final String c_idnumber, final String c_city, String c_frontface, String c_reverseside, String c_onecarphoto, String c_handheld, String c_headportrait, final String c_drivertype, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_token", c_token);
        hashMap.put("c_id", c_id);
        hashMap.put("c_name", c_name);
        hashMap.put("c_idnumber", c_idnumber);
        hashMap.put("c_city", c_city);
        hashMap.put("c_frontface", c_frontface);
        hashMap.put("c_reverseside", c_reverseside);
        hashMap.put("c_onecarphoto", c_onecarphoto);
        hashMap.put("c_handheld", c_handheld);
        hashMap.put("c_headportrait", c_headportrait);
        hashMap.put("c_drivertype", c_drivertype);
        hashMap.put("c_type", "2");
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.DRIVER_AUTHENTICATION, hashMap, DriverAuthenticationRequestBean.class, new OkGoRequests.OnTrue<DriverAuthenticationRequestBean>() {
            @Override
            public void hasData(final DriverAuthenticationRequestBean date) {
                if (date.isSuccess()) {
                    LiteOrmTools.getInformation(LogInformationBean.class, SmallMessageActivity.this, new LiteOrmTools.On<LogInformationBean>() {
                        @Override
                        public void hasData(LogInformationBean data) {
                            data.setC_city(c_city);
                            data.setC_drivertype(c_drivertype);
                            data.setC_idnumber(c_idnumber);
                            data.setC_name(c_name);
                            SingleLiteOrm.getSingleLiteOrm(SmallMessageActivity.this).SingleLite().update(data);
                        }
                    }, new LiteOrmTools.OFF() {
                        @Override
                        public void noData() {
                            LogInformationBean data = new LogInformationBean();
                            data.setC_city(c_city);
                            data.setC_drivertype(c_drivertype);
                            data.setC_idnumber(c_idnumber);
                            data.setC_name(c_name);
                            SingleLiteOrm.getSingleLiteOrm(SmallMessageActivity.this).SingleLite().insert(data);
                        }
                    });


                    Intent intent1 = new Intent(SmallMessageActivity.this, AuditActivity.class);
                    intent1.putExtra("status", date.getResult().getC_status());
                    startActivity(intent1);
                    finish();
                }
            }
        }, new OkGoRequests.OnError<DriverAuthenticationRequestBean>() {
            @Override
            public void noData() {

            }
        });

    }

    private Boolean judge(String name, String id, String city) {
        if (TextUtils.isEmpty(name)) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(this, "提示", "请填入姓名");
            baseHint.show();
            return false;
        }
        if (TextUtils.isEmpty(id) && id.length() == 18) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(this, "提示", "请输入正确的身份证号");
            baseHint.show();
            return false;
        }
        if (TextUtils.isEmpty(city)) {
            BaseHint baseHint = new BaseHint.addHint().setParameter(this, "提示", "请输选择城市");
            baseHint.show();
        }
        return true;
    }


    private void setCity() {
        CityPicker.getInstance().setFragmentManager(getSupportFragmentManager())
                .enableAnimation(true)
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        if (data != null) {
                            mCityTv.setText(data.getName());
                        }
                    }

                    @Override
                    public void onLocate() {
                        mLocationClient.start();
                    }
                }).show();
        mLocationClient.start();
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            city = location.getCity();
            String[] cityy = new String[0];
            if (!TextUtils.isEmpty(city)) {
                cityy = city.split("市");
            }
            province = location.getProvince();
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f
            int errorCode = location.getLocType();
            Log.d("111111", "errorCode:" + errorCode);
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            String addr = location.getAddrStr();
            mLocationClient.stop();
            if (errorCode == 161 || errorCode == 61) {
                CityPicker.getInstance()
                        .locateComplete(new LocatedCity(cityy[0], province, null), LocateState.SUCCESS);
            }

        }
    }

    private void setLocationClientOption() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationPoiList(true);

    }

    private void setIgPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
//        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(1);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(200);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(200);                         //保存文件的高度。单位像素
    }

    //上传图片
    private void initFileHtml(String fileBase64Str, String type, String c_token) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("fileBase64Str", fileBase64Str);
        hashMap.put("type", type);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", "2");
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_UPLOAD + UrlValuse.FILE, hashMap, FileRrequestBean.class, new OkGoRequests.OnTrue<FileRrequestBean>() {
            @Override
            public void hasData(FileRrequestBean date) {
                if (date.isSuccess()) {
                    mHeadPlace = date.getResult().getDbPath();
                    savePhotoToSD(mPhoneMp, mAccount + "HEAD_PHOTO");
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(SmallMessageActivity.this, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<FileRrequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private Bitmap comp(Bitmap image) {
        float scale = 768f / (float) image.getWidth();
        return compressImage(Bitmap.createScaledBitmap(image, 768,
                (int) (image.getHeight() * scale), false));
    }

    private Bitmap compressImage(Bitmap image) {

        Bitmap bitmap = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 40) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(
                baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片

        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            isBm.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 保存照片到SD卡的指定位置
     */
    private void savePhotoToSD(Bitmap bitmap, String name) {
        File outputImage = new File(Environment.getExternalStorageDirectory(), "/YGDDriver/Photo/" + name + ".jpg");
        if (!outputImage.getParentFile().exists()) {
            outputImage.getParentFile().mkdirs();
        }
        try {
            FileOutputStream fos = new FileOutputStream(outputImage);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
